package com.springcloud.authentication.modules.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.springcloud.authentication.common.RestResult;
import com.springcloud.authentication.common.RestResultEntity;
import com.springcloud.authentication.common.jwt.Audience;
import com.springcloud.authentication.common.jwt.JwtHelper;
import com.springcloud.authentication.modules.entity.SysPermission;
import com.springcloud.authentication.modules.entity.SysRole;
import com.springcloud.authentication.modules.entity.SysUser;
import com.springcloud.authentication.modules.repository.PermissionRepository;
import com.springcloud.authentication.modules.repository.RoleRepository;
import com.springcloud.authentication.modules.repository.UserRepository;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.SignatureException;
import io.jsonwebtoken.UnsupportedJwtException;

/**
 * @author Administrator
 *
 */
@Service
public class SysUserService {

	@Autowired
	private UserRepository sysUserDao;

	@Autowired
	private RoleRepository sysRoleDao;

	@Autowired
	private PermissionRepository sysPermissionDao;

	@Autowired
	private Audience audience;



	public List<SysUser> findList(){
		return sysUserDao.findAll();
	}
	
	/**
	 * 生成token
	 * @return
	 */
	public Map<String,Object> getToken(SysUser user){
		//生成token
		String accessToken = JwtHelper.createJWT(user.getName(),
				user.getId(),
				user.getRoleNames(),
				audience.getClientId(),
				audience.getName(),
				audience.getExpiresSecond(),
				audience.getBase64Secret());
		//刷新的token
		String refreshToken = JwtHelper.createJWT(user.getName(),
				user.getId(),
				user.getRoleNames(),
				audience.getClientId(),
				audience.getName(),
				audience.getRefreshSecond(),
				audience.getBase64Secret());
		Map<String, Object> map = new HashMap<>();
		map.put("accessToken", "bearer;"+accessToken);
		map.put("refreshToken", "bearer;"+refreshToken);
		return map;
	}

	/**
	 * 校验token
	 * @param token
	 * @return
	 */
	public RestResultEntity<?> verification (String token) {
		Claims claims = null;
		try {
			token  = token.substring(7);
			claims = JwtHelper.parseJWT(token,audience.getBase64Secret());
		} catch (ExpiredJwtException e) {
			return RestResult.genErrorResult("401","令牌过期"); 
		} catch (UnsupportedJwtException e) {
			return RestResult.genErrorResult("401","令牌无效"); 
		} catch (MalformedJwtException e) {
			return RestResult.genErrorResult("401","令牌格式错误"); 
		} catch (SignatureException e) {
			return RestResult.genErrorResult("401","令牌签名无效"); 
		} catch (IllegalArgumentException e) {
			return RestResult.genErrorResult("401","令牌参数异常"); 
		} catch (Exception e) {
			return RestResult.genErrorResult("401","令牌错误"); 
		}

		try {
			//验证用户信息
			String userid = claims.get("userid").toString();
			SysUser user = findById(userid);
			if (user == null) {
				return RestResult.genErrorResult("401","用户不存在"); 
			}
		} catch (Exception e) {
			return RestResult.genErrorResult("未知错误");
		}
		return RestResult.genResult(claims);
	}


	/**
	 * 用户id查找用户信息
	 * @param userId
	 * @return
	 */
	public SysUser findById(String userId){
		return sysUserDao.findById(userId);
	}


	/**
	 * 用户登录逻辑
	 * @param sysUser
	 * @return
	 */
	public SysUser getUser(String name,String pwd){
		SysUser user = sysUserDao.findByNameAndPwd(name,pwd);
		//查角色名称
		if (user != null) {
			List<SysRole> sysRoleList = sysRoleDao.findUserRoleList(user.getId());
			List<String> roles = new ArrayList<>();
			Set<String> permissions = new HashSet<>();
			user.setSysRole(sysRoleList);
			String roleNames = "";
			if(sysRoleList != null) {
				for (com.springcloud.authentication.modules.entity.SysRole sysRole : sysRoleList) {
					roleNames += sysRole.getName()+",";
					roles.add(sysRole.getName());
					//查权限
					List<SysPermission> findRolePermissionList = sysPermissionDao.findRolePermissionList(sysRole.getId());
					for (SysPermission sysPermission : findRolePermissionList) {
						permissions.add(sysPermission.getName());
					}
				}
				roleNames = roleNames.substring(0, roleNames.length()-1);//截取最后一个
				user.setRoleNames(roleNames);
				user.setRoles(roles);
				user.setSysPermission(permissions);
			}
		}
		return user;
	}


}
